<template>
    <div class="sport-type-container">
        <FilterSearch
            :searchItems="searchItems"
            :showAddButton="showAddButton"
            @query="handleQuery"
            @add="handleAdd"
        />
        <AutoTable
            :tableData="tableData"
            :columns="columns"
            @operate="handleOperate"
        />
        <Pagination
            :total="total"
            :pageSize="pageSize"
            :currentPage="currentPage"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
        <EditDialog
            ref="editDialogRef"
            :visible="editDialogVisible"
            :dialogType="editDialogType"
            :editItems="editItems"
            @successCallBack="editCallBack"
            @close="handleClose"
        />
    </div>
</template>
<script setup>
import './index.css';
import { reactive, ref, markRaw } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { View, Delete, Edit } from '@element-plus/icons-vue'

import FilterSearch from '@/components/filterSearch/index.vue';
import AutoTable from '@/components/autoTable/index.vue';
import Pagination from '@/components/pagination/index.vue';
import EditDialog from '@/components/editDialog/index.vue';


import { sportTypeApi } from '@/api';

// FilterSearch params
const searchItems = ref([
    {
      label: '运动名称',
      vModel: 'name',
      type: 'input',
      initialValue: ''
    }
]);  
const showAddButton = ref(true);
const searchCache = ref({});


// AutoTable params
const tableData = ref([]);
const columns = ref([
    {
      label: '运动名称',
      prop: 'name',
      width: '140px'
    },
    {
      label: '运动部位',
      prop: 'body_part',
      type: 'tag',
      getTag: item =>item.split(':')[0],
      getTips: item =>item.split(':')[0],
      width: '180px'
    },
    {
      label: '难度',
      prop: 'difficulty',
      type: 'progress',
      updateValue: item => item * 20,
      width: '120px'
    },
    {
      label: '效率',
      prop: 'efficiency',
      type: 'progress',
      updateValue: item => item * 20,
      width: '120px'
    },
    {
      label: '所需装备',
      prop: 'required_equipment',
      type: 'tag',
      getTag: item =>item.split(':')[0],
      getTips: item =>item.split(':')[0],
      width: '180px'
    },
    {
      label: '卡路里/分钟',
      prop: 'calories_per_minute',
      width: '120px'
    },
    {
      label: '操作',
      prop: 'operate',
      fixed: 'right',
      type: 'action',
      align: 'left',
      width: '140px',
      operate: [
        {label: '详情', type: 'view', icon: markRaw(View)},
        {label: '编辑', type: 'edit', icon: markRaw(Edit)}, 
        {label: '删除', type: 'delete', icon: markRaw(Delete)},
      ]
    }

]);

// Pagination params
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);

// edit Dialog params
const editDialogVisible = ref(false);
const editDialogType = ref('add');
const editItems = ref([
    {
      label: 'id',
      vModel: '_id',
      type: 'forbidden',
      initialValue: '',
    },
    {
      label: '运动名称',
      vModel: 'name',
      type: 'input',
      initialValue: '',
    },
    {
      label: '运动部位',
      vModel: 'body_part',
      type: 'tagInput',
      initialValue: []
    },
    {
      label: '难度',
      vModel: 'difficulty',
      type: 'Number',
      min: 0,
      max: 5,
      step: 1,
      initialValue: ''
    },
    {
      label: '效率',
      vModel: 'efficiency',
      type: 'Number',
      min: 0,
      max: 5,
      step: 1,
      initialValue: ''
    },
    {
      label: '所需装备',
      vModel: 'required_equipment',
      type: 'tagInput',
      initialValue: []
    },
    {
      label: '卡路里/分钟',
      vModel: 'calories_per_minute',
      type: 'input',
      initialValue: ''
    }
]);  

// filterSearch Api
const handleQuery = async (params) => {
    // 调用接口获取数据
    searchCache.value = params;
    const reqParams = {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        ...params
    }
    const res = await sportTypeApi.getSportType(reqParams);
    if (res.code === 200) {
      tableData.value = res.data.rows;
      total.value = res.data.total;
    }
};

// EditDialog Api
const handleAdd = () => {
    editDialogType.value = 'add';
    initEditItems({
        name: '',
        body_part: [],
        difficulty: 0,
        efficiency: 0,
        required_equipment: [],
        calories_per_minute: ''
    });
    editDialogVisible.value = true;
};
const editCallBack = async (type, params) => {
    if (type === 'add') handleAddCallBack(params);
    else if (type === 'edit') handleEditCallBack(params);
} 
const handleAddCallBack = async (params) => {
    const res = await sportTypeApi.createSportType(params);
    if (res.code === 200) {
        editDialogVisible.value = false;
        ElMessage.success('新增成功');
        handleQuery();
    }
}
const handleEditCallBack = async (params) => {
    const res = await sportTypeApi.updateSportType(params._id, params);
    if (res.code === 200) {
        editDialogVisible.value = false;
        ElMessage.success('变更成功');
        handleQuery();
    }
}
const handleClose = () => {
    editDialogVisible.value = false;
}

// Pagination Api
const handleSizeChange = (size) => {
    pageSize.value = size;
    handleQuery(searchCache.value);
};
const handleCurrentChange = (page) => {
    currentPage.value = page;
    handleQuery(searchCache.value);

};

// AutoTable Api
const handleOperate = (type, row) => {
    if (type === 'edit') {
      editDialogType.value = 'edit';
      initEditItems(row);
      editDialogVisible.value = true;

    }
    else if (type === 'view') {
      editDialogType.value = 'view';
      initEditItems(row);
      editDialogVisible.value = true;
    }
    else if (type === 'delete') {
      handleDelete(row);
    }
}
const initEditItems = (row) => {
  editItems.value.forEach(item => {
    item.initialValue = row[item.vModel];
  })
}
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定删除当前运动类型吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      const res = await sportTypeApi.deleteSportType(row._id)
      if (res.code === 200) {
        ElMessage({ type: 'success', message: '删除成功!' });
        handleQuery();
      }
    })
    .catch(() => {
      ElMessage({ type: 'info', message: '取消删除!' })
    })
}

</script>